// WordDataManager 现在通过全局实例使用

Component({
  properties: {},
  data: {
    totalWords: 0,
    showExportModal: false,
    exportOption: 'all',
    selectedBookIndex: -1,
    allBooksList: [],
    modalAnimation: null
  },
  lifetimes: {
    attached() {
      try {
        const app = getApp();
      this.dm = app.globalData.wordDataManager;
        const allBooks = this.dm.getAllBooks();
        let total = 0;
        allBooks.forEach(b => { total += (this.dm.getWordsByBookId(b.id) || []).length; });
        this.setData({ totalWords: total, allBooksList: allBooks });
        this.modalAnimation = wx.createAnimation({ duration: 300, timingFunction: 'ease' });
      } catch (e) {
        console.error('计算总单词数失败', e);
      }
    }
  },
  methods: {
    onRefresh() {
      try {
        const app = getApp();
      const dm = app.globalData.wordDataManager;
        const allBooks = dm.getAllBooks();
        let total = 0;
        allBooks.forEach(b => { total += (dm.getWordsByBookId(b.id) || []).length; });
        this.setData({ totalWords: total });
      } catch (e) {
        console.error('刷新总单词数失败', e);
      }
    },
    onManageTap() {
      wx.navigateTo({
        url: '/pages/category-manager/category-manager'
      });
    },
    openExportModal() {
      this.setData({ showExportModal: true, exportOption: 'all', selectedBookIndex: -1 });
      setTimeout(() => {
        this.modalAnimation.opacity(1).step();
        this.setData({ modalAnimation: this.modalAnimation.export() });
      }, 10);
    },
    closeExportModal() {
      this.modalAnimation.opacity(0).step();
      this.setData({ modalAnimation: this.modalAnimation.export() });
      setTimeout(() => { this.setData({ showExportModal: false }); }, 300);
    },
    selectExportOption(e) {
      const { option } = e.detail || e.currentTarget.dataset || {};
      if (option) this.setData({ exportOption: option });
    },
    onBookPickerChange(e) {
      const value = e && e.detail && (e.detail.value);
      if (value !== undefined && value !== null) {
        this.setData({ selectedBookIndex: parseInt(value) });
      }
    },
    confirmExport() {
      const { exportOption, selectedBookIndex, allBooksList } = this.data;
      wx.showLoading({ title: '导出中...' });
      try {
        if (exportOption === 'all') {
          const filePath = this.dm.exportDictionaryToTxt();
          this.shareExportedFile(filePath, '全部单词.txt');
        } else if (exportOption === 'book' && selectedBookIndex >= 0) {
          const bookId = allBooksList[selectedBookIndex].id;
          const bookName = allBooksList[selectedBookIndex].name;
          const filePath = this.dm.exportBookToTxt(bookId);
          this.shareExportedFile(filePath, `${bookName}.txt`);
        } else {
          throw new Error('请选择要导出的词书');
        }
      } catch (error) {
        wx.hideLoading();
        wx.showToast({ title: '导出失败：' + error.message, icon: 'none' });
      }
    },
    shareExportedFile(filePath, fileName) {
      wx.hideLoading();
      wx.shareAppMessage({
        title: `单词宝库 - ${fileName}`,
        path: '/pages/vocabulary/wordbook/wordbook',
        filePath: filePath,
        success: () => {
          this.setData({ showExportModal: false });
          wx.showToast({ title: '导出成功', icon: 'success' });
        },
        fail: (error) => {
          console.error('分享失败:', error);
          wx.showToast({ title: '导出成功，请手动分享', icon: 'none' });
          wx.saveFile({
            tempFilePath: filePath,
            success: (res) => {
              wx.openDocument({ filePath: res.savedFilePath, showMenu: true });
            }
          });
        }
      });
    }
  }
});
